package com.cande.loki.jmh.aeron;

import io.aeron.Aeron;
import io.aeron.CommonContext;
import io.aeron.Subscription;
import io.aeron.driver.MediaDriver;
import io.aeron.driver.ThreadingMode;
import io.aeron.logbuffer.FragmentHandler;
import org.agrona.concurrent.IdleStrategy;
import org.agrona.concurrent.SleepingIdleStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Receiver {


    private static final Logger logger = LoggerFactory.getLogger(Receiver.class);

    public static void main(String[] args) {

        final IdleStrategy idle = new SleepingIdleStrategy();

        final MediaDriver.Context mediaDriverCtx = new MediaDriver.Context()
                .aeronDirectoryName(CommonContext.getAeronDirectoryName() + "-client")
                .dirDeleteOnStart(true)
                .dirDeleteOnShutdown(true)
                .threadingMode(ThreadingMode.SHARED);


        MediaDriver driver = MediaDriver.launchEmbedded(mediaDriverCtx);
        final Aeron.Context aeronCtx = new Aeron.Context()
                .aeronDirectoryName(driver.aeronDirectoryName());

        Aeron aeron = Aeron.connect(aeronCtx);
        //这相当于是一个服务端，用于监听本机的端口
        Subscription sub = aeron.addSubscription("aeron:udp?endpoint=127.0.0.1:2000", 11);

        final FragmentHandler handler = (buffer, offset, length, header) ->
                logger.info("received:{}", buffer.getStringAscii(offset));

        while (true) {
            while (sub.poll(handler, 1) <= 0)
            {
                idle.idle();
            }
        }




    }

}
